package com.example.springbootjackson.traceId;

import org.slf4j.MDC;

import java.util.Map;

/**
 * @author jiangwenzhi
 */
public class MDCRunnable implements Runnable {

    private final Runnable runnable;

    private final Map<String, String> map;

    public MDCRunnable(Runnable runnable) {
        this.runnable = runnable;
        this.map = MDC.getCopyOfContextMap();
    }

    @Override
    public void run() {
        try {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                MDC.put(entry.getKey(), entry.getValue());
            }
            runnable.run();
        }finally {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                MDC.remove(entry.getKey());
            }
        }

    }
}
